import { debounceTime, switchMap, distinctUntilChanged, map } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService } from '@core/services/http/api.service';
import { ApesDialogComponent } from '@shared/dialog/apes-dialog.component';
import { ApesModalService } from '@shared/apes/modal';
import { dateFormat, isObject, replaceAll, type } from '../../utils/utils';
import { ApesMessageService } from '@shared/apes/message';
import { FormService } from '@core/services/form.service';


@Injectable()
export class SearchService {
  // , public dialog: MatDialog,
  constructor(private apiService: ApiService,
              private  msg: ApesMessageService,
              private modalService: ApesModalService,
              private formService: FormService) {
  }

  search(terms: Observable<any>, method: string, debounceMs = 500) {
    return terms.pipe(debounceTime(debounceMs),
      distinctUntilChanged(),
      switchMap(term => this.rawSearch(term, method)));
  }

  rawSearch(requestData: any, method: string) {
    return this.apiService.post(method, { 'body': JSON.stringify(requestData) });
  }

  openDialog(url: string, option: any, callback: any, dialog?: any): Observable<any> {

    return this.apiService.post('form.search.get', { 'body': JSON.stringify({ 'id': url }) }).pipe(
      map((body) => {
        body.result = [];
        if (typeof option === 'boolean') {
          body.rowSelection = option === true ? 'multiple' : 'single';
        } else if (typeof option === 'object') {
          body.rowSelection = option.multiple === true ? 'multiple' : 'single';
          for (let key in option) {
            if (option[key] === undefined || option === null) delete option[key];
          }
          body = { ...body, ...option };
        }
        // 加个参数条件判断
        // let openDialog;
        // if(body.dialog) {
        //   openDialog = DialogInquiryComponent;
        //   // openDialog = JSON.parse(body.dialog);
        // }else {
        //   openDialog = ApesDialogComponent;
        // }
        const openDialog = dialog ? dialog : ApesDialogComponent;
        const dialogRef = this.modalService.create({
          apesWidth: body.width ? body.width : '70vw',//1200
          apesTitle: body.title,
          // apesClassName: 'test-1',
          // apesWrapClassName: 'modal-lg',
          apesContent: openDialog,
          apesComponentParams: body,
          apesFooter: [
            {
              label: '取消',
              type: 'default',
              onClick: () => {
                dialogRef.close();
              },
            },
            {
              label: '确定',
              type: 'primary',
              disabled: (componentInstance) => {
                let disabled = true;
                if (componentInstance['multiple'] && componentInstance['resultsData'].length != 0) {
                  disabled = false;
                } else if (componentInstance['resultData'] != '' && componentInstance['resultData'] != null) {
                  disabled = false;
                }
                if (componentInstance['selectLastStage']) {
                  let data = componentInstance['resultData'];
                  if (!data[componentInstance['selectLastStage']]) {
                    disabled = true;
                  }
                }
                if (componentInstance['pureSearch']) return false;
                if (componentInstance.hasOwnProperty('compileComponent')) {
                  disabled = !componentInstance['form'].valid;
                }
                return disabled;
              },
              onClick: (componentInstance) => {
                if (componentInstance['multiple']) {
                  // console.log('选择结果', componentInstance['resultsData']);
                  dialogRef.destroy(componentInstance['resultsData']);
                } else {
                  if (componentInstance['pureSearch']) {
                    // 传递查询条件
                    dialogRef.destroy(componentInstance['getConditionList'](componentInstance['conditionField']));
                  } else {
                    dialogRef.destroy(componentInstance['resultData']);
                  }
                }
              },
            },
          ],
        });

        // 调用前的回调
        // dialogRef.afterOpen.subscribe();

        return dialogRef.afterClose.subscribe((result) => callback(result));
      }));
  }

  /**
   * 功能：拼接查询条件
   * @returns {any[]}
   */
  getConditionList(conditionField: any, model: any): any[] {
    const conditionList = [];
    for (const tempConditionField of conditionField) {
      let fieldKey = tempConditionField.key;
      const fieldValue = model[fieldKey];

      const config = tempConditionField.templateOptions.config;
      const required = config.required;

      // 判断查询的操作条件（=、like...）
      let operatorValue = '';
      if (config.value) {
        operatorValue = config.value;
      } else if (config.operators.length > 0) {
        operatorValue = config.operators[0];
      }

      // 判断是否必填
      if (required && !fieldValue) {
        this.msg.error(`${tempConditionField.templateOptions.label}为必填项`, { apesDuration: 5000 });
        return;
      }

      if ((!fieldValue && (config.type !== 'boolean')) || fieldValue === undefined || fieldValue === null || fieldValue.length === 0) {
        continue;
      }

      if (config.type === 'select') {
        if (model[fieldKey] && model[fieldKey + '_name']) {
          if (model[fieldKey] instanceof Array) {
            let items = [];
            model[fieldKey].forEach((item, index) => {
              items.push({
                id: item,
                name: model[fieldKey + '_name'][index],
              });
            });
            tempConditionField.templateOptions.componentRef.items = items;
          } else {
            let value = {
              id: model[fieldKey],
              name: model[fieldKey + '_name'],
            };
            tempConditionField.templateOptions.componentRef.items = [value];
          }
        }
      }

      // 处理存在明细表字段的情况
      fieldKey = replaceAll(fieldKey, '#', '.');

      if (config.type === 'dateRange') {
        let formatType = config.hasOwnProperty('valueFormatter') ? config['valueFormatter'] : 'yyyy-MM-dd';
        const dataModelStar = {
          field: fieldKey,
          operator: 'GTE',
          value: this.dateRangeFormat(formatType, fieldValue[0], 'GTE'),
          type: 'date',
        };
        const dataModelEnd = {
          field: fieldKey,
          operator: 'LTE',
          value: this.dateRangeFormat(formatType, fieldValue[1], 'LTE'),
          type: 'date',
        };

        conditionList.push(dataModelStar);
        conditionList.push(dataModelEnd);
      } else if (config.type === 'date') {
        const dataModel = { type: 'date' };

        dataModel['field'] = fieldKey;
        dataModel['operator'] = operatorValue ? operatorValue : 'EQ';
        dataModel['value'] = dateFormat('yyyy-MM-dd', fieldValue);
        conditionList.push(dataModel);
      } else if (config.type === 'boolean') {
        const dataModel = {};

        dataModel['field'] = fieldKey;
        dataModel['operator'] = operatorValue ? operatorValue : 'EQ';
        dataModel['value'] = fieldValue ? 1 : 0;
        conditionList.push(dataModel);
      } else {
        const dataModel = {};

        dataModel['field'] = fieldKey;
        dataModel['operator'] = operatorValue ? operatorValue : 'EQ';
        dataModel['value'] = type(fieldValue) === 'string' ? fieldValue.trim() : fieldValue;
        conditionList.push(dataModel);
      }
    }
    return conditionList;
  }

  dateRangeFormat(type, value, operator) {
    let date;
    if (type != 'yyyy-MM-dd') {
      date = dateFormat(type, value);
    } else {
      let ope = operator == 'GTE' ? ' 00:00:00' : ' 23:59:59';
      date = dateFormat(type, value) + ope;
    }
    return date;
  }

  openContextLink(data: any, method: string, params?: object) {
    if (isObject(params)) Object.assign(data, params);
    if (method == null) {
      this.msg.error('该链接尚未存在，麻烦核实！', { 'apesDuration': 5000 });
      return false;
    }
    if (params['OAInterface'] == false) {
      const formId = method;
      data['formId'] = formId;
      this.formService.navigateToForm(data);
      return;
    }
    this.apiService.post(method, { 'body': JSON.stringify(data) }).subscribe((item) => {
      if (data.changeSignFlag) item.changeSignFlag = data.changeSignFlag;
      if (data.wfFlag) item.wfFlag = data.wfFlag;
      if (data.OAInterface) item.OAInterface = data.OAInterface;

      this.formService.navigateToForm(item);
    });
  }

}
